#nullable enable

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using PHMEE.EnergyEfficiency;
using Volo.Abp;

namespace PHMEE.Admin.Controllers.DataSync;

[Route("phmeeadmin/api/data-sync")]
public class DataSyncController : PHMEEAdminController
{
    private readonly ITimeSeriesDataLogRepository _timeSeriesDataLogRepository;
    private readonly ILogger<DataSyncController> _logger;
    private readonly IConfiguration _configuration;

    public DataSyncController(ITimeSeriesDataLogRepository timeSeriesDataLogRepository,
        ILogger<DataSyncController> logger,
        IConfiguration configuration)
    {
        _timeSeriesDataLogRepository = timeSeriesDataLogRepository;
        _logger = logger;
        _configuration = configuration;
    }

    /// <summary>
    /// 岸端同步数据接口
    /// </summary>
    /// <param name="log"></param>
    /// <returns></returns>
    [AllowAnonymous]
    [Route("SyncData")]
    [HttpPost]
    public async Task<IActionResult> SyncDataAsync(TimeSeriesDataLog log)
    {
        try
        {
            bool isBoard = _configuration.GetValue<bool>("IsBoard");
            if (isBoard)
            {
                throw new UserFriendlyException("船端不允许调用此接口");
            }

            _logger.LogInformation(
                "保存船端同步过来的数据到数据库：VesselId: {vesselId}, OperationType: {operationType}, SyncDataType: {syncDataType}, TimeSeriesDataLogId: {timeSeriesDataLogId}",
                log.VesselId, log.OperationType, log.SyncDataType, log.Id);

            // 检查库中是否有该 Id 的数据
            var existingLog = await _timeSeriesDataLogRepository.FindOrDefaultAsync(log.Id);
            if (existingLog is not null)
            {
                // 如果库中已存在，说明这是重复的数据，直接返回
                return Ok(existingLog.Id);
            }

            // 插入数据库

            // 将 IsSynced 置为 false，等后台任务同步成功后再更新为 true
            log.IsSynced = false;

            var result = await _timeSeriesDataLogRepository.InsertAsync(log);
            return Ok(result.Id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "数据同步失败：VesselId: {vesselId}, OperationType: {operationType}, SyncDataType: {syncDataType}, TimeSeriesDataLogId: {timeSeriesDataLogId}",
                log.VesselId, log.OperationType, log.SyncDataType, log.Id);

            return BadRequest($"数据同步失败，Id: {log.Id}");
        }
    }
}